import axios from 'axios'

// const API_BASE_URL = 'http://localhost:8123/api'

// 根据环境变量设置 API 基础 URL
const API_BASE_URL = process.env.NODE_ENV === 'production'
    ? '/api' // 生产环境使用相对路径，适用于前后端部署在同一域名下
    : 'http://localhost:8123/api' // 开发环境指向本地后端服务


// 创建 axios 实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 生成聊天室 ID
export const generateChatId = () => {
  return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// AI 恋爱大师 SSE 连接
export const connectLoveAppSSE = (message, chatId, onMessage, onError, onComplete) => {
  const url = `${API_BASE_URL}/ai/love_app/chat/sse?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}`
  
  console.log('正在连接 SSE:', url)
  
  const eventSource = new EventSource(url)
  let isCompleted = false
  
  // 连接建立时的处理
  eventSource.onopen = (event) => {
    console.log('SSE 连接已建立')
  }
  
  eventSource.onmessage = (event) => {
    console.log('收到 SSE 数据:', event.data)
    
    if (event.data === '[DONE]') {
      console.log('SSE 流结束')
      isCompleted = true
      eventSource.close()
      onComplete && onComplete()
      return
    }
    
    try {
      const data = event.data
      onMessage && onMessage(data)
    } catch (error) {
      console.error('SSE 数据解析错误:', error)
      if (!isCompleted) {
        isCompleted = true
        eventSource.close()
        onError && onError(error)
      }
    }
  }
  
  eventSource.onerror = (error) => {
    console.error('SSE 连接错误:', error)
    console.error('错误详情:', {
      readyState: eventSource.readyState,
      url: eventSource.url
    })
    
    // 防止重复处理错误
    if (!isCompleted) {
      isCompleted = true
      eventSource.close()
      onError && onError(error)
    }
  }
  
  return eventSource
}

// AI 超级智能体 SSE 连接
export const connectManusSSE = (message, onMessage, onError, onComplete) => {
  const url = `${API_BASE_URL}/ai/manus/chat?message=${encodeURIComponent(message)}`
  
  console.log('正在连接 Manus SSE:', url)
  
  const eventSource = new EventSource(url)
  let isCompleted = false
  
  // 连接建立时的处理
  eventSource.onopen = (event) => {
    console.log('Manus SSE 连接已建立')
  }
  
  eventSource.onmessage = (event) => {
    console.log('收到 Manus SSE 数据:', event.data)
    
    if (event.data === '[DONE]') {
      console.log('Manus SSE 流结束')
      isCompleted = true
      eventSource.close()
      onComplete && onComplete()
      return
    }
    
    try {
      const data = event.data
      onMessage && onMessage(data)
    } catch (error) {
      console.error('SSE 数据解析错误:', error)
      if (!isCompleted) {
        isCompleted = true
        eventSource.close()
        onError && onError(error)
      }
    }
  }
  
  eventSource.onerror = (error) => {
    console.error('Manus SSE 连接错误:', error)
    console.error('错误详情:', {
      readyState: eventSource.readyState,
      url: eventSource.url
    })
    
    // 防止重复处理错误
    if (!isCompleted) {
      isCompleted = true
      eventSource.close()
      onError && onError(error)
    }
  }
  
  return eventSource
}

export default apiClient
